﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace GDPforecast.Models
{
    /// <summary>
    /// 利用最小二乘法公式计算回归方程参数、预测结果
    /// </summary>
    internal class OrdinaryLeastSaures
    {
        #region
        /// <summary>
        /// X序列记录年份
        /// </summary>
        public static List<int> X = new List<int>() { 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 };
        /// <summary>
        /// Y序列记录历年GDP
        /// </summary>
        public static List<double> Y = new List<double>() { 1.21, 1.34, 1.47, 1.66, 1.96, 2.29, 2.75, 3.55, 4.59, 5.1, 6.09, 7.55, 8.53, 9.57, 10.48, 11.06, 11.23, 12.31, 13.89, 14.28, 14.69 };
        /// <summary>
        /// 总年数
        /// </summary>
        public static int N = X.Count;
        /// <summary>
        /// X求和
        /// </summary>
        public int Xsum = X.Sum();
        /// <summary>
        /// Y求和
        /// </summary>
        public double Ysum = Y.Sum();
        /// <summary>
        /// 回归方程中的参数a和b(b为系数）
        /// </summary>
        private double a { get; set; }
        private double b { get; set; }
        #endregion
        public void compute()
        {
            double c = 0, d = 0;
            double AvgX = X.Average();
            double AvgY = Y.Average();
            //计算公式中的XiYi求和和Xi平方求和
            for (int i = 0; i < N; i++)
            {
                c += X[i]*Y[i];
                d += X[i]*X[i];
            }
            //带入各部分值，求出a、b
            b = (N*c-Xsum*Ysum)/(N*d-Xsum*Xsum);
            a = AvgY-b*AvgX;
        }
        //代入数据，预测结果
        public double Forecast(double x)
        {
            return b*x+a;
        }

    }
}
